<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    
  </style>
</head>
<body>
  <input type="text" class="un"><br>
  <input type="text" class="pw"><br>
  <input type="button" class="btn" value="注册">
</body>
<script>

  $(".btn").onclick = function(){
    ajaxPost({
      url:"http://localhost:3000/register",
      data:{
        username:$(".un").value,
        password:$(".pw").value
      },
      success:res=>{
        console.log(res);
      }
    })
  }


  function ajaxPost({url, success, error, data}){
    let str = "";
    for(let i in data){
      str += `${i}=${data[i]}&`;
    }
    // url = url + "?" + str.slice(0, -1);
    const xhr = new XMLHttpRequest();

    // 1. open的第一个参数
    xhr.open("post", url);
    // 2. 配置请求数据的解析格式
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    // 3. post发送数据的位置为send的参数
    xhr.send(str.slice(0, -1));

    xhr.onreadystatechange = function(){
      if(xhr.readyState === 4 && xhr.status === 200){
        success(xhr.responseText);
      }else if( xhr.readyState === 4 && xhr.status !== 200 ){
        error && error(xhr.status);
      }
    }
  }
  


  function $(s){
    return document.querySelector(s)
  }
</script>
</html>